<template>
  <div class="container">
    <el-card v-loading="loading" class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $route.query.id ? '试题修改' : '试题录入' }}</span>
      </div>
      <div class="formitem">
        <el-form ref="form" label-width="120px" :model="formData" :rules="rules">
          <el-form-item label="学科：" prop="subjectID">
            <el-select v-model="formData.subjectID" placeholder="请选择" @change="subjectIDChange">
              <el-option
                v-for="item in xueKeSimples"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="formData.catalogID" placeholder="请选择">
              <el-option
                v-for="item in muLuLists"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="formData.enterpriseID" placeholder="请选择">
              <el-option
                v-for="item in enterpriseIDLists"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" class="two-select" prop="city">
            <el-select v-model="formData.province" placeholder="请选择" @change="cityChange">
              <el-option
                v-for="(item, index) in provinces"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
            <!-- city -->
            <el-select v-model="formData.city" placeholder="请选择">
              <el-option
                v-for="(item, index) in citys"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="方向：" prop="direction">
            <el-select v-model="formData.direction" placeholder="请选择">
              <el-option
                v-for="(item,index) in direction"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group v-model="formData.questionType" @change="optionsChange({})">
              <el-radio v-for="item in questionType" :key="item.value" :label="item.value+''">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="formData.difficulty">
              <el-radio v-for="item in difficulty" :key="item.value" :label="item.value+''">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 富文本编辑器 -->
          <el-form-item label="题干：" prop="question">
            <quill-editor v-model="formData.question" :options="editorOptions" style="height: 250px; margin-bottom: 70px" @change="checkQustion" />
          </el-form-item>
          <!-- 富文本编辑器 -->
          <el-form-item v-if="formData.questionType !== '3'" label="选项：">
            <!-- <el-radio-group v-model="formData.options.code" > -->
            <!-- 单选 -->
            <div v-if="formData.questionType === '1'">
              <el-row v-for="(item,index) in formData.options" :key="item.code" style="margin-bottom: 20px;" type="flex" justify="start" align="middle">
                <el-radio v-model="item.isRight" :label="true" style="margin-right: 9px" @change="optionsChange(item)">{{ item.code + ':' }}</el-radio>

                <el-input v-model="formData.options[index].title" style="width:250px" />
                <el-upload
                  style="margin-left:4px"
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :headers="{'Authorization':'Bearer '+ token}"
                  :on-success="(res,file)=>{uploadSuccess(item,res,file)}"
                  :show-file-list="false"
                  list-type="picture-card"
                >
                  <img v-if="item.img" :src="item.img" class="avatar">
                  <span v-else>上传图片</span>
                  <i class="el-icon-circle-close" />
                </el-upload>
              </el-row>
            </div>
            <!-- </el-radio-group> -->
            <!-- 多选 -->
            <div v-if="formData.questionType === '2'">
              <el-row v-for="(item,index) in formData.options" :key="item.code" style="margin-bottom: 20px;" type="flex" justify="start" align="middle">
                <el-checkbox v-model="item.isRight" :label="true" style="margin-right: 9px">{{ item.code + ':' }}</el-checkbox>

                <el-input v-model="formData.options[index].title" style="width:250px" />

                <el-upload
                  style="margin-left:4px"
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :headers="{'Authorization':'Bearer '+ token}"
                  :on-success="(res,file)=>{uploadSuccess(item,res,file)}"
                  :show-file-list="false"
                  list-type="picture-card"
                >
                  <img v-if="item.img" :src="item.img" class="avatar">
                  <span v-else>上传图片</span>
                  <i class="el-icon-circle-close" />
                </el-upload>
              </el-row>
            </div>

            <el-row><el-button type="danger" size="medium" :disabled="formData.questionType !== '2'" @click="addOption"><i class="el-icon-plus" />增加选项与答案</el-button></el-row>

          </el-form-item>

          <el-form-item label="解析视频：">
            <el-input v-model="formData.videoURL" style="width:400px" />
          </el-form-item>

          <el-form-item label="答案解析" prop="answer">
            <quill-editor v-model="formData.answer" :options="editorOptions" style="height: 250px; margin-bottom: 70px" @change="checkAnswer" />
          </el-form-item>

          <el-form-item label="题目备注：">
            <el-input v-model="formData.remarks" style="width:400px" type="textarea" rows="4" />
          </el-form-item>

          <el-form-item label="试题标签：" prop="tags">
            <el-select
              v-model="formData.tags"
              placeholder="请选择"
              multiple
              filterable
              allow-create
              default-first-option
            >
              <el-option
                v-for="item in tagsLists"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit">{{ $route.query.id ? '确认修改' : '确认提交' }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/questions'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, difficulty, questionType } from '@/api/hmmm/constants'
import { simple } from '@/api/hmmm/subjects'
import { simple as muLuList } from '@/api/hmmm/directorys'
import { list as enterpriseIDList } from '@/api/hmmm/companys'
import { simple as tagsList } from '@/api/hmmm/tags'
import { quillEditor } from 'vue-quill-editor'
import { getToken } from '@/utils/auth'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  name: 'Ononeon',
  components: {
    quillEditor
  },
  data () {
    return {
      loading: false,
      token: getToken(),
      selectCode: true,
      // 富文本配置
      // 1. 使用 highlight.js 插件处理高亮
      // 2. 安装  npm i highlight.js
      // 3. 导入  代码语法风格的样式   转换文本插件
      // 4. 配置 富文本  实时输入的时候高亮效果
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      difficulty,
      questionType,
      provinces: [],
      citys: [],
      direction: [],
      xueKeSimples: [],
      muLuLists: [],
      enterpriseIDLists: [],
      tagsLists: [],
      formData: {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: null, // 城市
        city: null, // 地区
        direction: null, // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: null, // 题干
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '' // 题目备注
        // tags: ''// 试题标签
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'change' }
        ],
        tags: [
          { required: true, message: '请输入试题标签', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.provinces = provinces()
    this.direction = direction
    this.simple()
    this.enterpriseIDList()
    // this.tagsList()
    if (this.$route.query.id) {
      this.gitDetail()
    }
  },
  methods: {
    // 富文本编辑器
    catchData1 (item) {
      this.formData.question = item
    },
    catchData2 (item) {
      this.formData.answer = item
    },
    questionTypeChange () {
      // console.log(this.formData.questionType)
    },
    difficultyChange () {
      // console.log(this.formData.difficulty)
    },
    optionsChange (item) {
      // 1. 清除所有的选中
      this.formData.options.forEach(item => {
        item.isRight = false
      })
      // 2. 自己选中
      item.isRight = true
    },
    cityChange () {
      this.formData.city = null
      this.citys = citys(this.formData.province)
    },
    async subjectIDChange (subjectID) {
      // console.log(subjectID);
      // this.formData.subjectID = null
      this.formData.catalogID = null
      const res1 = await muLuList({subjectID})
      this.muLuLists = res1.data
      this.formData.tags = null
      const res2 = await tagsList({subjectID})
      this.tagsLists = res2.data
    },
    async simple () {
      const { data } = await simple()
      this.xueKeSimples = data
    },
    async enterpriseIDList () {
      const { data: { items } } = await enterpriseIDList({ pagesize: 10000 })
      this.enterpriseIDLists = items
      // console.log(items)
    },
    // async tagsList () {
    //   const { data } = await tagsList()
    //   this.tagsLists = data
    // },
    addOption () { // 点击新增选项
      this.formData.options.push({
        code: String.fromCharCode(65 + this.formData.options.length),
        title: '',
        img: '',
        isRight: false
      })
    },
    checkQustion () { // 验证富文本
      this.$refs.form.validateField('question')
    },
    checkAnswer() { // 验证富文本
      this.$refs.form.validateField('answer')
    },
    async gitDetail () { // 编辑 根据id 获取题目详情
      // console.log('编辑')
      const { data } = await detail({ id: this.$route.query.id })
      // console.log(data)
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.formData = data
      const res = await muLuList(this.formData.subjectID)
      this.muLuLists = res.data
      const res2 = await tagsList(this.formData.subjectID)
      this.tagsLists = res2.data

      // this.muLuLists =
      // data.catalogID
    },
    // 确认提交
    async onSubmit () {
      // console.log(this.formData)
      await this.$refs.form.validate(async isOK => {
        if (isOK) {
          this.loading = true
          const data = { ...this.formData }
          // console.log(data)
          data.tags = data.tags.join(',')
          try {
            if (this.$route.query.id) {
            // console.log('编辑')
            // this.formData.options.forEach((value, index) => {
            //   if (value.code === this.formData.options.code) {
            //     this.formData.options[index].isRight = true
            //   }
            // })
              await update(data)
              this.$message.success('修改成功')
            } else {
            // console.log('新增')
            // console.log('新增')
            // const data = { ...this.formData }
            // console.log(data)
            // data.tags = data.tags.join(',')
              await add(data)
              this.$message.success('添加成功')
              // console.log(data)
            }
            this.$router.push('/questions/list')
            this.loading = false
          } catch (e) {
            console.log(e)
          }
        }
      })
    },
    uploadSuccess (item, res, file) {
      // res 是相应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      try {
        item.img = URL.createObjectURL(file.raw)
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.container{
  ::v-deep.el-loading-mask{
    z-index: 1!important;
  }
}

.container{
  padding: 20px;
}
.text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
.formitem{
  padding-left: 50px;
  .el-select{
    width: 400px;
  }
  .two-select{
    .el-select{
      padding-right: 5px;
      width: 203px;
    }
  }
}

  .fuwenben{
    ::v-deep.w-e-toolbar{
      z-index: 0!important;
    }
    ::v-deep.w-e-text-container{
      border: 1px solid #c9d8db!important;
      border-top: none!important;
      height: 200px!important;
      z-index: 0!important;
    }
}
.avatar-uploader{
  ::v-deep .el-upload--picture-card{
    width: 100px;
    height: 60px;
    margin-left: 4px;
    z-index: 1;
    position: relative;
    span {
      display: block;
      width: 100px;
      height: 60px;
      line-height:60px;
      color: black;
      font-size:15px;
    }
    i{
      font-size:20px;
      position: absolute;
      right: -10px;
      top: -9px;
    }
  }
}
</style>
